
//
//  IndexViewController.m
//  Estate
//
//  Created by heyong on 16/5/25.
//  Copyright © 2016年 ttsx. All rights reserved.

#import "CommonFunc.h"
#import "GJDBViewController_Detail.h"
#import "SGFDBDetailViewController.h"
#import "PictureViewController.h"
#import "Bugly.h"
#import "MyDownloadViewController.h"
#import "EditImageView.h"
#import "ProjectModel.h"
#import "ProcessModel.h"
#import "DBYSDetailViewController.h"
#import "FollowInCell.h"
#import "NewInspectionTextCell.h"
#import "RJTableCell.h"
#import "YJHBViewController.h"
#import "ZJRZViewController_Detail.h"
#import "addZJRJViewController.h"
#import "JLYSViewController_detail.h"
#import "IndexViewController.h"

@interface IndexViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
    UITableView *tableViews;
    NSString *record_type;
    //判断是否是甲方 巡检页面
    BOOL _isXJJF;
    TimeingSynchronization *_sync;
}
/**注释 */
@property (nonatomic,strong) EditImageView *editImageView;
//数据库
@property(nonatomic, strong)FMDatabase *db;
@property(nonatomic, strong)NSMutableArray *array;
@property(nonatomic, strong)NSMutableDictionary *dict;
@property(nonatomic, strong)NSString *status;

//项目模型
@property (nonatomic, strong)ProjectModel *model;

// 待处理事项数据
@property (nonatomic, strong)NSMutableArray *dataArray;

@property(strong,nonatomic)UIImagePickerController *imagePickerController;


@end


@implementation IndexViewController
- (UIImagePickerController *)imagePickerController{
    if(!_imagePickerController){
        _imagePickerController = [[UIImagePickerController alloc] init];
        _imagePickerController.delegate=self;
    }
    return _imagePickerController;
}


- (indexView *)indexView{
    if(_indexView==nil){
        _indexView=[[indexView alloc]initWithFrame:CGRectMake(0, 64, 375*BIZ, 667*BIZ)];
        _indexView.controller=self;
    }
    return _indexView;
}
- (NSMutableArray *)array{
    if(_array==nil){
        _array=[NSMutableArray array];
    }
    return _array;
}
- (NSMutableDictionary *)dict{
    if(_dict==nil){
        _dict=[NSMutableDictionary dictionaryWithCapacity:0];
    }
    return _dict;
}
- (ProjectModel *)model{
    if(_model==nil){
        _model=[[ProjectModel alloc]init];
    }
    return _model;
}

- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDir = [paths objectAtIndex:0];
    NSLog(@"%@",docDir);
    
   [LSHttpTool checkNetWork:^(NSString *status) {
        if(![status isEqualToString:@"0"]){
            self.isNet=YES;
        }else{
            self.isNet=NO;
        }
    }];
    
    self.isNet=YES;
    /*
     *  甲方  巡检员  巡检组长 显示今日天气
     */
    
    NSString *role=DEF_PERSISTENT_GET_OBJECT(@"role");
    if([USERTYPE.typeArray containsObject:role]){
        _isXJJF=YES;
    }else{
        _isXJJF=NO;
    }
    
    [self cteateView];
    //获得数据库地址
    self.db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    
    [self refresh:nil];
   
    //签到签退
    [self quertProject];
    
    //轮播图代理
    [self refreshAdv];
    
    //注册通知
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(refresh:) name:@"indexView" object:nil];
    
    //广告
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshAdv) name:@"refreshAdv" object:nil];
    
    // 刷新待处理事项
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadNotToDealWithData) name:@"home" object:nil];
    
    //检测未同步的数据
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkSyncSucceed) name:@"checkSyncSucceed" object:nil];
    
    // 刷新是否同步按钮
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(settingSyncBtn:) name:@"indexReloadBtn" object:nil];
    
    //天气
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(operateAPI) name:@"weatherRe" object:nil];
    
    //签到 签退
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(quertProject) name:@"signIn" object:nil];
    
    [self reloadNotToDealWithData];
    
    //默认同步按钮隐藏
    self.downHidden=YES;
    self.upHidden=YES;
    
    //页面显示出 刷新待处理角标
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [[NSNotificationCenter defaultCenter]postNotificationName:@"home" object:nil];
        //先检验一次是服务器是否有数据下载
        _sync=[[TimeingSynchronization alloc]init];
    });
    
    
    //登录成功之后 设置推送通知
    [LSUtility pushNotification];
    //设置关键数据，随崩溃信息上报
    NSString *userName = [CommonFunc textFromBase64String
                          :DEF_PERSISTENT_GET_OBJECT(@"loginuser")];
    NSString *passWord = [NSString stringWithFormat:@"%@",[CommonFunc textFromBase64String:DEF_PERSISTENT_GET_OBJECT(@"password")]];
    NSString *realname = DEF_PERSISTENT_GET_OBJECT(@"realname");
    [Bugly setUserValue:DEFISNUL(userName) forKey:@"loginuser"];
    [Bugly setUserValue:DEFISNUL(passWord) forKey:@"password"];
    [Bugly setUserValue:DEFISNUL(realname) forKey:@"realname"];


}

-(void)viewWillAppear:(BOOL)animated{
    NSLog(@"DB:%@",DEF_DB_DATABASEPATH);
    [self operateAPI];
}

// 刷新待处理事项数据
- (void)reloadNotToDealWithData {
    NSString *role=DEF_PERSISTENT_GET_OBJECT(@"role");
    if ([role isEqualToString:@"USER_01"]) {
        // 获取待处理信息(总监)
        [self getPendingMattersZJ];
    } else if ([role isEqualToString:@"USER_03"]||[role isEqualToString:@"USER_07"]) {
        // 获取待处理信息(监理)
        [self getPendingMattersJL];
    }
    [tableViews reloadData];
}

/*
 *  检测本地数据是否上传成功
 */

- (void)checkSyncSucceed {
    /*
     *  检测本地是否有数据同步上传
     */
    BOOL isOk = false;
    for (NSString *table in TABLEDATA.tableArray) {
        isOk = [self queayLocalDataContainAddOrModByTableFormsg:table];
        if(isOk) {
            if(self.syncType&&![self.syncType isEqualToString:@""]){
                [MBProgressHUD showError:self.syncType toView:self.view];
            }
            break;
        }
    }
    [_sync isSyncLocalData];
}

//创建视图
- (void)cteateView{
    self.view.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:self.indexView];
    tableViews = self.indexView.tableView;
    tableViews.delegate = self;
    tableViews.dataSource = self;
    
    [tableViews registerNib:[UINib nibWithNibName:@"FollowInCell" bundle:nil] forCellReuseIdentifier:@"follCell"];
    [tableViews registerNib:[UINib nibWithNibName:@"NewInspectionTextCell" bundle:nil] forCellReuseIdentifier:@"detail"];
    [tableViews registerNib:[UINib nibWithNibName:@"RJTableCell" bundle:nil] forCellReuseIdentifier:@"RJCell"];
    
    //签到签退
    UIButton *qiandao=self.indexView.qianDaoBtn;
    qiandao.tag=100;
    [qiandao addTarget:self action:@selector(jumpQianD:) forControlEvents:UIControlEventTouchUpInside];
    
    //项目切换
    UIButton *qiehuan=self.indexView.qieHuanBtn;
    qiehuan.tag=101;
    [qiehuan addTarget:self action:@selector(jumpQianD:) forControlEvents:UIControlEventTouchUpInside];
    //同步按钮
    UIButton *syncBtn=self.indexView.tongbuBtn;
    [syncBtn addTarget:self action:@selector(clickBtn) forControlEvents:UIControlEventTouchUpInside];
    
    //本地图片
    UIButton * photoBtn=self.indexView.photoBtn;
    photoBtn.tag=102;
    [photoBtn addTarget:self action:@selector(jumpQianD:) forControlEvents:UIControlEventTouchUpInside];
    
    //搜索下载
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"sousuo_1"] style:UIBarButtonItemStyleDone target:self action:@selector(download)];
}

#pragma mark -数据同步
- (void)clickBtn {
    [LSHttpTool checkNetWork:^(NSString *status) {
        if(![status isEqualToString:@"0"]){
            self.isNet=YES;
        }else{
            self.isNet=NO;
        }
    }];
    DataSynchronization *data = [[DataSynchronization alloc] init];
    [data syncDataFromTable:self.view refresh:YES isNet:self.isNet andExit:NO];
}

#pragma  mark- 设置同步图标
- (void)settingSyncBtn:(NSNotification *)notifi{
    //判断个人设置是否打开定时刷新 打开才进行判断
    NSMutableDictionary *settingDic=DEF_PERSISTENT_GET_OBJECT(USERID);
    if(settingDic){
        //得到本地存储的刷新频率设置
        if(settingDic){
            //开启了定时器
            if([settingDic[@"isTiming"] isEqualToString:@"yes"]){
                NSDictionary *dic=notifi.userInfo;
                self.downHidden=YES;
                NSInteger num=[dic[@"isHiden"]integerValue];
                //等于0 就是有更新
                if(num==0){
                    self.downHidden=NO;
                }else{
                    self.downHidden=YES;
                }
                //设置图标 是否隐藏
                self.indexView.ishidden= self.downHidden;
            }else{
                self.downHidden=YES;
                self.indexView.ishidden=  self.downHidden;
            }
            //设置图标类型
            if(self.downHidden){
                //判断本地是否有需要上传的文件
                if(!self.upHidden){
                    self.indexView.ishidden=NO;
                    self.indexView.iconType=@"sc";
                }else{
                    self.indexView.ishidden=YES;
                }
            }else{
                //有上传 有下载
                if(!self.upHidden){
                    self.indexView.iconType=@"scxz";
                }else{
                    self.indexView.iconType=@"xz";
                }
#pragma mark 此处新增方法 发送通知

                UILocalNotification *localNotification = [[UILocalNotification alloc] init];
                //设置时区（跟随手机的时区）
                localNotification.timeZone = [NSTimeZone defaultTimeZone];
                localNotification.fireDate = [NSDate date];
                localNotification.alertBody = @"有您新内容，待更新！";
                //设置userinfo方便撤销
                localNotification.userInfo = @{@"name":@"有您新内容，待更新！"};
                localNotification.soundName = UILocalNotificationDefaultSoundName;
                //启动任务
                [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
                
                
            }
        }
    }else{
        self.indexView.ishidden=YES;
    }
}

#pragma  mark -刷新数据
- (void)refresh:(id)sender {
    //得到本地图库
    NSString *fullPath=DEF_IMAGEFILE_PATH;
    NSFileManager*fileManager = [NSFileManager defaultManager];
    NSArray*fileList = [[NSArray alloc]init];
    fileList=[fileManager contentsOfDirectoryAtPath:fullPath error:nil];
    //本地图片右上角数字
    self.indexView.photoNum.text=[NSString stringWithFormat:@"%li",fileList.count];
    //查询签到列表
    [self operateDataBase];
    // 获取当前角色
    NSString *role=DEF_PERSISTENT_GET_OBJECT(@"role");
    if ([role isEqualToString:@"USER_01"]) {
        // 获取待处理信息(总监)
        [self getPendingMattersZJ];
    } else if ([role isEqualToString:@"USER_03"]||[role isEqualToString:@"USER_07"]) {
        // 获取待处理信息(监理)
        [self getPendingMattersJL];
    }
    [tableViews reloadData];
}

#pragma  mark -更新广告
- (void)refreshAdv{
    NSDictionary *advDic = [LSUtility queryAdvAttachment:@"1332d771-aea5-42ca-a995-2f0cfd57320c"];
    if (advDic) {
        NSLog(@"有附件");
    }else{
        NSLog(@"没有附件");
    }
    //设置轮播图条数
    NSDictionary *dic=[LSUtility querySystemConfig:ADVERTISING_NUMBER];
    
    long num=[dic[@"CONFVALUE"] integerValue];
    //最多用10条
    num=num>=10?10:num;
    
    //查询所有广告
    self.advArr= [LSUtility queryAllAdvertiseMent];
    
    NSLog(@"%@",self.advArr);
    //广告条数 比配置的多
    if(self.advArr.count>num){
        self.advArr=[[self.advArr subarrayWithRange:NSMakeRange(0, num)] mutableCopy];
    }
    self.advImageArr=[NSMutableArray array];
    //查询广告本地图片
    for (NSDictionary *dic in self.advArr) {
        //查找附件
        NSDictionary *advDic = [LSUtility queryAdvAttachment:dic[@"ID"]];
        if(advDic){
            NSString *fileName=advDic[@"FILE_NAME"];
            NSString *filePath=[DEF_FILE_PATH stringByAppendingString:
                                [NSString stringWithFormat:@"/%@",fileName]];
            [self.advImageArr addObject:filePath];
        }
    }
    self.indexView.advArr=self.advImageArr;
    self.indexView.cycleScrollView2.delegate=self;
}

#pragma mark- 跳转至下载
- (void)download{
    MyDownloadViewController *downCtr = [[MyDownloadViewController alloc]init];
    downCtr.isSearch = YES;
    [self.navigationController pushViewController:downCtr animated:YES];
}

#pragma --mark btn-method
-(void)jumpQianD:(UIButton *)sender{
    if(sender.tag==100){
        [LSHttpTool checkNetWork:^(NSString *status) {
            if(![status isEqualToString:@"0"]){
                self.isNet=YES;
            }else{
                self.isNet=NO;
            }
        }];
        [self singInConfiguration];
    }else if(sender.tag==101){
        QieHViewController *qieH=[[QieHViewController alloc]init];
        qieH.indexProName = self.model.projectName;
        [self.navigationController pushViewController:qieH animated:YES];
    }else{
        /*
         * 调用APP内部相册
         **/
        PictureViewController *pic=[[PictureViewController alloc]init];
        [self.navigationController pushViewController:pic animated:YES];
    }
}

#pragma mark- 查询签到签退配置
-(void)singInConfiguration{
    if(self.isNet){
        //查询能否ping通
        NSString *check=[API_HOST stringByAppendingString:@"/mobile/checkConn.do"];
        NSMutableDictionary *dic=[NSMutableDictionary dictionary];
        [LSUtility showMBProgress:self.view message:@"网络校验中..."];
        [LSHttpTool PostCheckIP:check parameters:dic success:^(id responseObject) {
            NSString *code=responseObject[@"code"];
            [LSUtility hideMBProgress:self.view];
            if([code isEqualToString:@"1"]){
                //查询本地数据表
                NSString *con=[LSUtility queryProjectExtendInfoForId:PROID];
                //1是允许离线 历史数据为“”
                if([con isEqualToString:@""]||[con isEqualToString:@"1"]){
                    self.isServerTime=NO;
                }else{
                    self.isServerTime=YES;
                }
                [self singInCamera];
            }else{
                [LSUtility showToastWithMessage:@"此项目不允许离线签到,请确保网络通畅后再进行签到/签退!" inView:self.view Andtime:3];
            }
            
        } failure:^(NSError *error) {
            [LSUtility hideMBProgress:self.view];
            [LSUtility showToastWithMessage:@"此项目不允许离线签到,请确保网络通畅后再进行签到/签退!" inView:self.view Andtime:3];
        }];
    }
    //无网
    else{
        //查询本地数据表
        NSString *con=[LSUtility queryProjectExtendInfoForId:PROID];
        //1是离线 历史数据为“”
        if([con isEqualToString:@""]||[con isEqualToString:@"1"]){
            self.isServerTime=NO;
            [self singInCamera];
            
        }else{
            [LSUtility showToastWithMessage:@"此项目不允许离线签到,请确保网络通畅后再进行签到/签退!" inView:self.view Andtime:3.2];
        }
    }
}

//签到退 调用相机
-(void)singInCamera{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        
        self.imagePickerController.sourceType = sourceType;
        if(iOS8Later) {
            self.imagePickerController.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        }
        [self presentViewController:self.imagePickerController animated:YES completion:nil];
        self.tabBarController.tabBar.hidden=YES;
    } else {
        NSLog(@"模拟器中无法打开照相机,请在真机中使用");
    }
}

#pragma  mark-  天气
#pragma  mark-  天气
- (void)operateAPI {
    /*
     *  检测本地是否有数据同步
     */
    //如果隐藏执行本地表方法
    for (NSString *table in TABLEDATA.tableArray) {
        self.upHidden = [self queayLocalDataContainAddOrModByTable:table];
        if(!self.upHidden) {
            NSLog(@"本地做更改的表:%@",table);
            break;
        }
    }
    
    //本地无数据上传 判断是否有数据下载
    if(self.upHidden){
        //有数据下载
        if(!self.downHidden){
            self.indexView.iconType=@"xz";
        }else{
            self.indexView.ishidden=YES;
        }
    }else{
        //有数据下载
        if(!self.downHidden){
            self.indexView.iconType=@"scxz";
        }else{
            self.indexView.iconType=@"sc";
            self.indexView.ishidden=NO;
        }
    }
    
    /*
     *  获得天气
     //     */
    NSString *role = DEF_PERSISTENT_GET_OBJECT(@"role");
    
    if (![role isEqualToString:@"LEADER_01"]) {
        NSMutableDictionary *parmeDic=[NSMutableDictionary dictionary];
        // 得到该项目的项目概览的code
        NSDictionary *cityDic=[LSUtility queryProengineerSurvey:PROID];
        NSArray *cityCodeArr = [cityDic allKeys];
        NSString *cityCodeStr = @"";
        for (NSString *cityCode in cityCodeArr) {
            if (cityCodeStr.length>0) {
                cityCodeStr = [NSString stringWithFormat:@"%@,%@",cityCodeStr,cityCode];
            }else{
                cityCodeStr = cityCode;
            }
        }
        
        [parmeDic setObject:@"getWeather" forKey:@"service"];
        [parmeDic setObject:cityCodeStr forKey:@"weather_code"];
        
        
        AFHTTPRequestSerializer *httpRequestSerializer = [AFJSONRequestSerializer serializer];
        httpRequestSerializer.timeoutInterval = 30;
        httpRequestSerializer.cachePolicy = NSURLRequestUseProtocolCachePolicy;
        NSMutableURLRequest *request = [httpRequestSerializer requestWithMethod:@"POST" URLString:URL_WEATHER parameters:parmeDic error:NULL];
        AFHTTPSessionManager *operationManager = [AFHTTPSessionManager manager];
        operationManager.responseSerializer = [AFHTTPResponseSerializer serializer];
        [operationManager.responseSerializer setAcceptableContentTypes: [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", nil]];
        
        [[operationManager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
            if (error) {
                NSLog(@"--->HTTP请求错误：%@",error);
                [self noWeather];
                [LSUtility showToastWithMessage:@"天气获取失败" inView:self.view Andtime:1.];

            } else {
                NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
                NSLog(@"%@",dic);
                NSArray *array = dic[@"weather_list"];
                if (array.count>0) {
                    [self getWeather:array];
                }else{
                    [self noWeather];
                }
            }
        }] resume];
    }else{
        NSLog(@"不进行天气请求");
    }
}
-(void)noWeather{
    NSMutableArray *weatherArr=[NSMutableArray array];
    NSMutableDictionary *weaDic=[NSMutableDictionary dictionary];
    [weaDic setObject:@"无法获取天气信息" forKey:@"无"];
    [weatherArr addObject:weaDic];
    DEF_PERSISTENT_SET_OBJECT(weatherArr, @"WEATHER");
}
-(void)getWeather:(NSArray *)dataArr{
    NSLog(@"%@",dataArr);
    NSDictionary *cityDic=[LSUtility queryProengineerSurvey:PROID];
    NSArray *cityCodeArr = [cityDic allKeys];
    NSArray *cityNameArr =[cityDic allValues];
    NSMutableArray *weatherArr=[NSMutableArray array];
    for (NSDictionary *dataDic in dataArr) {
        NSMutableDictionary *weaDic=[NSMutableDictionary dictionary];
        NSString *code=dataDic[@"cityCode"];
        if(![dataDic[@"city"] isEqual:[NSNull null]]){
            //项目概览包含此城市 添加
            if([cityCodeArr containsObject:code]){
                NSString *city = dataDic[@"city"];
                if([dataDic[@"city"] isEqual:[NSNull null]]){
                    city = @"";
                }
                NSString *wea=dataDic[@"weather"];
                if([dataDic[@"weather"] isEqual:[NSNull null]]){
                    wea = @"";
                }
                NSString *temp=dataDic[@"temp"];
                if([dataDic[@"temp"] isEqual:[NSNull null]]){
                    temp = @"";
                }
                NSString *weather=[NSString stringWithFormat:@"%@ %@℃",wea,temp];
                if (temp.length>0&&[temp containsString:@"℃"]) {
                    weather=[NSString stringWithFormat:@"%@ %@",wea,temp];
                }
                if(!temp||temp.length<=0){
                    weather = @"无法获取天气信息";
                }
                [weaDic setObject:weather forKey:city];
                [weatherArr addObject:weaDic];
            }else{
                NSLog(@"项目概览中无法匹配到城市");
            }
        }
    }
    //接口无天气
    if(weatherArr.count==0){
        //判断本地城市有的话就写
        if (cityNameArr.count>0) {
            for(NSString *city in cityNameArr){
                NSLog(@"%@",city);
                NSMutableDictionary *weaDic=[NSMutableDictionary dictionary];
                [weaDic setObject:@"无法获取天气信息" forKey:city];
                [weatherArr addObject:weaDic];
            }
            //本地没有城市
        }else{
            NSMutableDictionary *weaDic=[NSMutableDictionary dictionary];
            [weaDic setObject:@"无法获取天气信息" forKey:@"无"];
            [weatherArr addObject:weaDic];
        }
    }
    DEF_PERSISTENT_SET_OBJECT(weatherArr, @"WEATHER");
    if(_isXJJF){
        [self.array removeAllObjects];
        [self.array addObject:DEF_PERSISTENT_GET_OBJECT(@"WEATHER")];
        [tableViews reloadData];
    }
}

#pragma mark-数据库操作(获取签到信息)
- (void)operateDataBase {
    [self.db open];
    [self.array removeAllObjects];
    if(_isXJJF&&DEF_PERSISTENT_GET_OBJECT(@"WEATHER")){
        [self.array addObject:DEF_PERSISTENT_GET_OBJECT(@"WEATHER")];
    } else {
        NSString *sql=@"";
        if([DEFROLE isEqualToString:@"USER_01"]){
            sql=[NSString stringWithFormat:@"SELECT * FROM WORK_RECORD WHERE RECORD_TYPE IN('RECORD_05','RECORD_06') AND PRO_ID='%@' AND RECORD_USER='%@' and STATE='0' ORDER by CREATE_TIME DESC",PROID,USERID];
        }else if([DEFROLE isEqualToString:@"USER_03"]||[DEFROLE isEqualToString:@"USER_07"]){
            sql=[NSString stringWithFormat:@"SELECT * FROM WORK_RECORD WHERE RECORD_TYPE IN('RECORD_05','RECORD_06') AND PRO_ID='%@' AND RECORD_USER='%@' and STATE='1' ORDER by CREATE_TIME DESC",PROID,USERID];
        }else{
            sql=[NSString stringWithFormat:@"SELECT * FROM WORK_RECORD WHERE RECORD_TYPE IN('RECORD_05','RECORD_06') AND PRO_ID='%@' AND RECORD_USER='%@' and STATE='2' ORDER by CREATE_TIME DESC",PROID,USERID];
        }
        // 数据库操作 签到签退查看
        FMResultSet *resultSet = [self.db executeQuery:sql];
        // 遍历结果
        while ([resultSet next]) {
            //用户id
            NSString *id=[resultSet stringForColumn:@"RECORD_USER"];
            //类型
            NSString *type = [resultSet stringForColumn:@"RECORD_TYPE"];
            [self.dict setObject:type forKey:@"type"];
            //用户
            NSString *name=[self userById:id];
            [self.dict setObject:DEFISNUL(name) forKey:@"name"];
            //拼接字符串
            [self.dict setObject:[resultSet stringForColumn:@"RECORD_TITLE"] forKey:@"cellText"];
            //时间
            NSString *time=[resultSet stringForColumn:@"CREATE_TIME"];
            [self.dict setObject:time forKey:@"time"];
            //附件id
            NSString *fileId=[resultSet stringForColumn:@"RECORD_FILE_PATH"];
            NSArray *arrs=[LSUtility indexDictionaryWithJsonString:fileId];
            NSDictionary *fileDic=[arrs firstObject];
            
            if(fileDic){
                [self.dict setObject:fileDic[@"fileId"] forKey:@"fileId"];
            }
            //地区 天气
            NSString *addAndWea=[resultSet stringForColumn:@"WEATHER"];
            NSArray *arr=[addAndWea componentsSeparatedByString:@"/"];
            //天气
            [self.dict setObject:DEFISNUL(arr[0]) forKey:@"address"];
            //地区
            [self.dict setObject:DEFISNUL([arr lastObject]) forKey:@"weather"];
            //记录地点
            NSString *addInfo=[resultSet stringForColumn:@"ADDRES_INFO"];
            [self.dict setObject:DEFISNUL(addInfo) forKey:@"addInfo"];
            
            //添加到数组
            [self.array addObject:self.dict];
            //设置为nil 不然数组内值一样
            self.dict=nil;
        }
    }
    [self.db close];
}

// 获取待处理事项(总监)
- (void)getPendingMattersZJ {
    [self.db open];
    [self.dataArray removeAllObjects];
    
    // 获取跟进
    NSString *sqlGJ = [NSString stringWithFormat:@"SELECT * FROM PROCESS WHERE PRO_ID = '%@' AND PROCESS_STAGE IN(%d,%d) AND PROCESS_TYPE = '2' ORDER BY CREATE_TIME DESC", PROID,PROCESS_STAGE_REVIEW,PROCESS_STAGE_CHECK_PASS_YES];
    
    FMResultSet *resultGJ = [self.db executeQuery:sqlGJ];
    // 遍历结果
    while ([resultGJ next]) {
        NSDictionary *dic=[resultGJ resultDictionary];
        
        ProcessModel *pModelGJ = [ProcessModel yy_modelWithDictionary:dic];
        
        if (pModelGJ.ID) {
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            [dic setObject:@"default" forKey:@"TYPE"];
            [dic setObject:pModelGJ forKey:@"DATA"];
            //添加到数组
            [self.dataArray addObject:dic];
        }
    }
    // 获取督办
    NSString *sqlDB2 = [NSString stringWithFormat:@"SELECT * FROM PROCESS WHERE PRO_ID = '%@'  AND PROCESS_STAGE IN(%d,%d) AND PROCESS_TYPE = '1' ORDER BY CREATE_TIME DESC", PROID,PROCESS_STAGE_REVIEW,PROCESS_STAGE_CHECK_PASS_YES];
    FMResultSet *resultDB2 = [self.db executeQuery:sqlDB2];
    // 遍历结果
    while ([resultDB2 next]) {
        NSDictionary *dic=[resultDB2 resultDictionary];
        ProcessModel *pModelDB2 = [ProcessModel yy_modelWithDictionary:dic];
        if (pModelDB2.ID) {
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            [dic setObject:@"default" forKey:@"TYPE"];
            [dic setObject:pModelDB2 forKey:@"DATA"];
            //添加到数组
            [self.dataArray addObject:dic];
        }
    }
    // 获取验收
//    NSString *sqlYS = [NSString stringWithFormat:@"SELECT *,time(CREATE_TIME) FROM PROCESS WHERE PRO_ID = '%@' AND ID IN(SELECT PROCESS_ID FROM PROCESS_RECORD) AND PROCESS_STAGE IN(401,402) AND PROCESS_TYPE = '3' ORDER BY CREATE_TIME DESC", PROID];
//    FMResultSet *resultYS = [self.db executeQuery:sqlYS];
//    // 遍历结果
//    while ([resultYS next]) {
//        ProcessModel *pModelYS = [[ProcessModel alloc] init];
//
//        pModelYS.ID = [resultYS stringForColumn:@"ID"];
//        pModelYS.PRO_ID = [resultYS stringForColumn:@"PRO_ID"];
//        pModelYS.ADDRESS_ID = [resultYS stringForColumn:@"ADDRESS_ID"];
//        pModelYS.ADDRES_INFO = [resultYS stringForColumn:@"ADDRES_INFO"];
//        pModelYS.PROCESS_TYPE = [resultYS intForColumn:@"PROCESS_TYPE"];
//        pModelYS.PROCESS_STAGE = [resultYS intForColumn:@"PROCESS_STAGE"];
//        pModelYS.PROCESS_PUBLISHERS = [resultYS stringForColumn:@"PROCESS_PUBLISHERS"];
//        pModelYS.PROCESS_MASTERS = [resultYS stringForColumn:@"PROCESS_MASTERS"];
//        pModelYS.PROCESS_RECIFY_USERS = [resultYS stringForColumn:@"PROCESS_RECIFY_USERS"];
//        pModelYS.PROCESS_RECIFY_UNITS = [resultYS stringForColumn:@"PROCESS_RECIFY_UNITS"];
//        pModelYS.RECIFY_REVIEW_USERS = [resultYS stringForColumn:@"RECIFY_REVIEW_USERS"];
//        pModelYS.BEGIN_TIME = [resultYS stringForColumn:@"BEGIN_TIME"];
//        pModelYS.REQUIRED_END_TIME = [resultYS stringForColumn:@"REQUIRED_END_TIME"];
//        pModelYS.END_TIME = [resultYS stringForColumn:@"END_TIME"];
//        pModelYS.PROCESS_TITLE = [resultYS stringForColumn:@"PROCESS_TITLE"];
//        pModelYS.PROCESS_NUMBER = [resultYS stringForColumn:@"PROCESS_NUMBER"];
//        pModelYS.EXTEND_INFO = [resultYS stringForColumn:@"EXTEND_INFO"];
//        pModelYS.CREATE_USER_NAME = [resultYS stringForColumn:@"CREATE_USER_NAME"];
//        pModelYS.CREATE_TIME = [resultYS stringForColumn:@"CREATE_TIME"];
//        pModelYS.CREATE_DETAIL_TIME=[resultYS stringForColumn:@"time(CREATE_TIME)"];
//        pModelYS.CREATE_IP = [resultYS stringForColumn:@"CREATE_IP"];
//        pModelYS.MODIFY_USER_NAME = [resultYS stringForColumn:@"MODIFY_USER_NAME"];
//        pModelYS.MODIFY_IP = [resultYS stringForColumn:@"MODIFY_IP"];
//        pModelYS.MODIFY_TIME = [resultYS stringForColumn:@"MODIFY_TIME"];
//
//        if (pModelYS.ID) {
//            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
//            [dic setObject:@"ys" forKey:@"TYPE"];
//            [dic setObject:pModelYS forKey:@"DATA"];
//            //添加到数组
//            [self.dataArray addObject:dic];
//        }
//    }
    // 获取巡检
    // 根据年查找巡检流程
    NSString *sqlXJ = [NSString stringWithFormat:@"SELECT *, substr(INSPECT_START_TIME, 1, 4) as YEAR, substr(INSPECT_START_TIME, 6, 2) as MONTH, substr(INSPECT_START_TIME, 9, 2) as DAY FROM INSPECT_PROCESS WHERE PRO_ID = '%@' AND INSPECT_STATE = '3' ORDER BY INSPECT_START_TIME DESC", PROID];
    FMResultSet *resultXJ = [self.db executeQuery:sqlXJ];
    
    while ([resultXJ next]) {
        
        // 巡检流程ID
        NSString *inspectProcessID = [resultXJ stringForColumn:@"ID"];
        // 巡检名称
        NSString *inspectName = [resultXJ stringForColumn:@"INSPECT_NAME"];
        // 巡检流程创建月
        NSString *month = [resultXJ stringForColumn:@"MONTH"];
        // 巡检流程创建日
        NSString *day = [resultXJ stringForColumn:@"DAY"];
        // 任务状态
        NSString *state = [resultXJ stringForColumn:@"INSPECT_STATE"];
        // 二级标题
        NSString *secondTitle = [NSString stringWithFormat:@"%@月%@日_%@", month, day, inspectName];
        // 每条任务数据
        NSDictionary *rowDic = @{@"INSPECT_PROCES_ID":inspectProcessID, @"SECOND_TITLE":secondTitle, @"STATE":state};
        
        if (rowDic[@"INSPECT_PROCES_ID"] && ![rowDic[@"INSPECT_PROCES_ID"] isEqualToString:@""]) {
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            [dic setObject:@"inspection" forKey:@"TYPE"];
            [dic setObject:rowDic forKey:@"DATA"];
            //添加到数组
            [self.dataArray addObject:dic];
        }
    }
    
    // 日记
    NSString *sqlRJ=[NSString stringWithFormat:@"select *,substr(DIARY_TIME,1,10) AS Day from WORK_DIARY WHERE PRO_ID = '%@' AND  REVIEW_USER = '%@' AND REVIEW_STATE = '0' ORDER BY DIARY_TIME desc", PROID, USERID];
    
    FMResultSet *resultRJ = [self.db executeQuery:sqlRJ];
    
    while ([resultRJ next]) {
        //id
        NSString *ids=[resultRJ stringForColumn:@"ID"];
        //获得天
        NSString *day=[resultRJ stringForColumn:@"Day"];
        //标题
        NSString *title=[NSString stringWithFormat:@"%@日记",day];
        //时间
        NSString *time=[resultRJ stringForColumn:@"CREATE_TIME"];
        //状态
        int state=[resultRJ intForColumn:@"REVIEW_STATE"];
        //记录人
        NSString *logUserId=[resultRJ stringForColumn:@"DIARY_USER"];
        
        NSString *recordName=[LSUtility getuserIdByUserName:logUserId][@"REAL_NAME"];
        
        NSDictionary *dict=@{@"id":ids,@"title":title,@"time":time,@"state":[NSString stringWithFormat:@"%i",state],@"recordName":DEFISNUL(recordName) ,@"recordId":logUserId};
        
        if (dict[@"id"] && ![dict[@"id"] isEqualToString:@""]) {
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            [dic setObject:@"diary" forKey:@"TYPE"];
            [dic setObject:dict forKey:@"DATA"];
            //添加到数组
            [self.dataArray addObject:dic];
        }
    }
    
    // 日志
    NSString *sqlRZ=[NSString stringWithFormat:@"SELECT substr(CREATE_TIME,1,10) AS Day,* FROM WORK_LOG WHERE PRO_ID = '%@' AND LOG_USERS != '%@' AND REVIEW_STATE = '0' ORDER BY CREATE_TIME desc ", PROID, USERID];
    
    FMResultSet *resultRZ = [self.db executeQuery:sqlRZ];
    
    while ([resultRZ next]) {
        //id
        NSString *ids=[resultRZ stringForColumn:@"ID"];
        //判断是日志类型
        NSString *type=[resultRZ stringForColumn:@"LOG_TYPE"];
        //获得天
        NSString *day=[resultRZ stringForColumn:@"Day"];
        
        //标题
        NSString *title;
        if([type isEqualToString:@"LOG_01"]){
            title =[NSString stringWithFormat:@"%@项目监理日志",day];
        }else if([type isEqualToString:@"LOG_02"]){
            title =[NSString stringWithFormat:@"%@项目安全日志",day];
        }
        
        //时间
        NSString *time=[resultRZ stringForColumn:@"CREATE_TIME"];
        
        //状态
        int staint=[resultRZ intForColumn:@"REVIEW_STATE"];
        NSString *state=staint==0?@"待审阅":@"已审阅";
        
        //记录人
        // NSString *logUserId=[results stringForColumn:@"LOG_USERS"];
        NSString *recordName=[resultRZ stringForColumn:@"CREATE_USER_NAME"];
        
        NSDictionary *dict=@{@"id":ids,@"title":title,@"time":time,@"state":state,@"recordName":recordName,@"type":type};
        
        if (dict[@"id"] && ![dict[@"id"] isEqualToString:@""]) {
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            [dic setObject:@"log" forKey:@"TYPE"];
            [dic setObject:dict forKey:@"DATA"];
            //添加到数组
            [self.dataArray addObject:dic];
        }
    }
    
    [self.db close];
    
}

// 获取待处理事项(监理)
- (void)getPendingMattersJL {
    [self.db open];
    
    [self.dataArray removeAllObjects];
    
    // 获取跟进 待复查 待执行
    NSString *sqlGJ = [NSString stringWithFormat:@"SELECT * FROM PROCESS WHERE PRO_ID = '%@' and ((PROCESS_PUBLISHERS='%@' AND PROCESS_STAGE IN(%d)) OR (PROCESS_RECIFY_USERS='%@' AND PROCESS_STAGE IN(%d))) AND PROCESS_TYPE = '2'  ORDER BY CREATE_TIME DESC", PROID,USERID,PROCESS_STAGE_CHECK,USERID,PROCESS_STAGE_DOING];
    [self addData:sqlGJ fromDB:self.db];
    
     //此处需要改为 PROCESS_MASTERS负责人下的 待复查 和 PROCESS_RECIFY_USERS执行人下的待执行 不然都能查出来为待办
    // 获取督办
    NSString *sqlDB = [NSString stringWithFormat:@"SELECT * FROM PROCESS WHERE PRO_ID = '%@' AND ((PROCESS_MASTERS = '%@' AND PROCESS_STAGE IN(%d,%d)) OR (PROCESS_RECIFY_USERS = '%@' AND PROCESS_STAGE IN(%d))) AND PROCESS_TYPE = '1' ORDER BY CREATE_TIME DESC", PROID,USERID,PROCESS_STAGE_REVIEW_PASS_NO,PROCESS_STAGE_CHECK,USERID,PROCESS_STAGE_DOING];
    [self addData:sqlDB fromDB:self.db];

    // 获取验收
    NSString *sqlYS = [NSString stringWithFormat:@"SELECT *,time(CREATE_TIME) FROM PROCESS WHERE PRO_ID = '%@' AND PROCESS_MASTERS = '%@' AND ID IN(SELECT PROCESS_ID FROM PROCESS_RECORD) AND PROCESS_STAGE IN(1, 4,402) AND PROCESS_TYPE = '3' ORDER BY CREATE_TIME DESC", PROID, USERID];
    
    FMResultSet *resultYS = [self.db executeQuery:sqlYS];
    // 遍历结果
    while ([resultYS next]) {
        NSDictionary *dic=[resultYS resultDictionary];
        ProcessModel *pModelYS = [ProcessModel yy_modelWithDictionary:dic];
        
        if (pModelYS.ID) {
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            [dic setObject:@"ys" forKey:@"TYPE"];
            [dic setObject:pModelYS forKey:@"DATA"];
            //添加到数组
            [self.dataArray addObject:dic];
        }
    }
    [self.db close];
}
-(void)addData:(NSString *)sqlGJ fromDB:(FMDatabase *)db
{
    FMResultSet *resultGJ = [db executeQuery:sqlGJ];
    // 遍历结果
    while ([resultGJ next]) {
        
        NSDictionary *dic=[resultGJ resultDictionary];
        ProcessModel *pModelGJ = [ProcessModel yy_modelWithDictionary:dic];
        
        if (pModelGJ.ID) {
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            [dic setObject:@"default" forKey:@"TYPE"];
            [dic setObject:pModelGJ forKey:@"DATA"];
            //添加到数组
            [self.dataArray addObject:dic];
        }
    }
}

#pragma mark-项目状态查看
- (void)quertProject{
    [self.db open];
    self.model.projectName=DEF_PERSISTENT_GET_OBJECT(@"proname");
    //设置项目id
    self.model.projectId=DEF_PERSISTENT_GET_OBJECT(@"proid");
    //添加模型到视图
    self.indexView.proModel=self.model;
    //判断是否签到
    NSString *sql=[NSString stringWithFormat:@"select *  from work_record where  pro_id='%@' and RECORD_USER='%@' and RECORD_TYPE in('RECORD_05','RECORD_06') order by create_time",DEF_PERSISTENT_GET_OBJECT(@"proid"),DEF_PERSISTENT_GET_OBJECT(@"userid")];
    FMResultSet *resultSet = [self.db executeQuery:sql];
    while ([resultSet next]) {
        record_type=[resultSet stringForColumn:@"RECORD_TYPE"];
    }
    [self.db close];
    /*
     *  甲方  巡检员  巡检组长 显示在岗 不进行判断
     */
    NSString *role=DEF_PERSISTENT_GET_OBJECT(@"role");
    if([USERTYPE.typeArray containsObject:role]||[USERTYPE.typeArrayNoWeather containsObject:role]) {
        self.indexView.labFlag.text=@"在岗";
        self.indexView.labFlag.backgroundColor=[UIColor colorWithRed:0.08 green:0.59 blue:0.53 alpha:1.00];
    }else{
        //已经签到 显示在岗 签退
        if([record_type isEqualToString:@"RECORD_05"]){
            self.indexView.state=1;
            self.indexView.labFlag.text=@"在岗";
            self.indexView.labFlag.backgroundColor=[UIColor colorWithRed:0.08 green:0.59 blue:0.53 alpha:1.00];
        }else{//未签到  显示离岗 签到
            self.indexView.state=0;
            self.indexView.labFlag.text=@"离岗";
            self.indexView.labFlag.backgroundColor=[UIColor colorWithRed:0.58 green:0.58 blue:0.59 alpha:1.00];
        }
    }
}

//查询用户
- (NSString *)userById:(NSString *)id
{
    NSString *sql=[NSString stringWithFormat:@"SELECT * FROM USER WHERE ID='%@'",id];
    FMResultSet *resultSet = [self.db executeQuery:sql];
    NSString *name;
    while ([resultSet next]) {
        name = [resultSet stringForColumn:@"REAL_NAME"];
    }
    return name;
}

#pragma mark-UIImagePicokerController

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    self.tabBarController.tabBar.hidden=NO;
    [self dismissViewControllerAnimated:YES completion:nil];
    UIImage *image=[info objectForKey:UIImagePickerControllerOriginalImage];

    self.editImageView = [[EditImageView alloc]initWithImage:image];
    //跳转到签到
    QianDViewController *qdView=[[QianDViewController alloc]init];
    
    //照片赋值
    qdView.isServer= self.isServerTime;
    //状态赋值
    if([record_type isEqualToString:@"RECORD_05"]){
        qdView.recordType=@"RECORD_05";
    }else{
        qdView.recordType=@"RECORD_06";
    }
    WEAKSELF
    self.editImageView.completeBlock = ^(NSString *path) {
        qdView.image = weakSelf.editImageView.imageEidtView.image ;
        [weakSelf.navigationController pushViewController:qdView animated:YES];
    };
    
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self.tabBarController.tabBar setHidden:NO];
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma -mark tabbleViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSString *role = DEF_PERSISTENT_GET_OBJECT(@"role");
    
    if([USERTYPE.typeArrayNoWeather containsObject:role]){
        return 0;
    } else if ([role isEqualToString:@"USER_01"] || [role isEqualToString:@"USER_03"]|| [role isEqualToString:@"USER_07"]) {
        return self.dataArray.count;
    } else {
        return _array.count;
    }
}

#pragma -mark-tableViewDataSourse

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    long row = indexPath.row;
    
    // 获取当前角色
    NSString *role=DEF_PERSISTENT_GET_OBJECT(@"role");
    
    if (_isXJJF) {
        indexTableCell *cell = [tableView dequeueReusableCellWithIdentifier:@"index" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        NSArray *arr = self.array[indexPath.row];
        NSDictionary *dic = [arr firstObject];
        NSString *city = [[dic allKeys]firstObject];
        NSString *title=@"";
        if(!city){
            title=@"无法获取当前天气！";
        }else{
            title = [NSString stringWithFormat:@"[%@] %@",city,[dic objectForKey:city]];
        }
        cell.qiandaoUser.text=title;
        cell.line.backgroundColor=[UIColor colorWithRed:0.00 green:0.59 blue:0.53 alpha:1.00];
        cell.qiandaoDate.text=[LSUtility nowTime];
        return cell;
        
        // 当前角色为总监
    } else if ([role isEqualToString:@"USER_01"] || [role isEqualToString:@"USER_03"]|| [role isEqualToString:@"USER_07"]) {
        NSDictionary *dic = [self.dataArray objectAtIndex:row];
        
        // 督办,跟进
        if ([dic[@"TYPE"] isEqualToString:@"default"]) {
            FollowInCell *cell = [tableView dequeueReusableCellWithIdentifier:@"follCell" forIndexPath:indexPath];
            cell.backgroundColor = [UIColor colorWithRed:0.97 green:0.97 blue:0.97 alpha:1.0];
            ProcessModel *pModel = dic[@"DATA"];
            
            // 时差
            NSString *shicha;
            if ([pModel.REQUIRED_END_TIME isEqual:@""]) {
                shicha = @"0";
            } else {
                NSTimeInterval  timeInterval = [LSUtility getDifftimeByTime:pModel.REQUIRED_END_TIME];
                long temp = timeInterval / 3600;
                if (timeInterval >= 0) {
                    temp = temp + 1;
                } else if (timeInterval < 0) {
                    temp = temp - 1;
                }
                shicha = [NSString stringWithFormat:@"%ld", temp];
            }
            shicha = [shicha stringByAppendingString:@"H"];
            // 时分秒
            NSString *time = [pModel.CREATE_TIME substringFromIndex:11];
            
            [cell setTitle:pModel.PROCESS_TITLE andDeTime:time andTime:shicha andState:(int)pModel.PROCESS_STAGE andProcessType:0];
            
            // 查询发送类型
            FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
            [db open];
            NSString *sql = [NSString stringWithFormat:@"SELECT SEND_TYPE FROM PROCESS_RECORD WHERE PROCESS_ID = '%@'", pModel.ID];
            FMResultSet *resulet = [db executeQuery:sql];
            int sendType = 8;
            while ([resulet next]) {
                sendType = [resulet intForColumn:@"SEND_TYPE"];
                break;
            }
            [db close];
            
            // 流程阶段
            NSInteger state = pModel.PROCESS_STAGE;
            // 跟进单
            if (pModel.PROCESS_TYPE == 1) {
                if (state == PROCESS_STAGE_REVIEW) {
                    cell.state.text = @"待审阅";
                    
                } else if (state == PROCESS_STAGE_REVIEW_PASS_NO) {
                    cell.state.text = @"审阅不通过";
                    
                } else if (state == PROCESS_STAGE_CHECK) {
                    cell.state.text = @"待复查";
                    
                } else if (state == PROCESS_STAGE_CHECK_PASS_YES) {
                    cell.state.text = @"复查通过";
                    
                } else if (state == PROCESS_STAGE_END) {
                    cell.state.text = @"结束";
                }
                // 督办单
            } else if (pModel.PROCESS_TYPE == 2) {
                if (state == PROCESS_STAGE_CHECK) {
                    cell.state.text = @"待复查";
                    
                } else if (state == PROCESS_STAGE_CHECK_PASS_YES) {
                    cell.state.text = @"复查通过";
                    
                } else if (state == PROCESS_STAGE_END) {
                    cell.state.text = @"结束";
                }
            }
            return cell;
            
        } else if ([dic[@"TYPE"] isEqualToString:@"inspection"]) {
            NewInspectionTextCell *cell = [NewInspectionTextCell cellWithTableView:tableView];
            NSDictionary *dics = dic[@"DATA"];
            
            // 列表标题
            cell.title.text = dics[@"SECOND_TITLE"];
            cell.title.numberOfLines = 0;
            cell.textLabel.font = [UIFont systemFontOfSize:16.*BIZ];
            
            if ([dics[@"STATE"] isEqualToString:@"3"]) {
                cell.state.text = @"待整改";
                
            } else if ([dics[@"STATE"] isEqualToString:@"4"]) {
                cell.state.text = @"待审阅";
                
            } else if ([dics[@"STATE"] isEqualToString:@"5"]) {
                cell.state.text = @"已完成";
            }
            return  cell;
            
            //验收
        } else if ([dic[@"TYPE"] isEqualToString:@"ys"]){
            ProcessModel *model=dic[@"DATA"];
            
            RJTableCell *cell=[tableView dequeueReusableCellWithIdentifier:@"RJCell" forIndexPath:indexPath];
            cell.line.backgroundColor=[UIColor colorWithRed:0.37 green:0.24 blue:0.36 alpha:1.00];
            
            cell.selectionStyle=UITableViewCellSelectionStyleNone;
            
            cell.title.text=model.PROCESS_TITLE;
            cell.time.text=model.CREATE_DETAIL_TIME;
            
            cell.name.text=[LSUtility getuserIdByUserName:model.PROCESS_PUBLISHERS][@"REAL_NAME"];
            
            if (model.PROCESS_STAGE == PROCESS_STAGE_START || model.PROCESS_STAGE == PROCESS_STAGE_REVIEW || model.PROCESS_STAGE == PROCESS_STAGE_CHECK) {
                cell.state.text = @"待验收";
            } else if (model.PROCESS_STAGE == PROCESS_STAGE_CHECK_PASS_YES_NO || model.PROCESS_STAGE == PROCESS_STAGE_DOING || model.PROCESS_STAGE == PROCESS_STAGE_REVIEW_PASS_NO) {
                cell.state.text = @"不合格";
            } else if (model.PROCESS_STAGE == PROCESS_STAGE_END || model.PROCESS_STAGE == PROCESS_STAGE_CHECK_PASS_YES || model.PROCESS_STAGE == PROCESS_STAGE_REVIEW_PASS_YES) {
                cell.state.text = @"合格";
            }
            
            return cell;
            // 日记/日志
        }else{
            NSDictionary *dataD = dic[@"DATA"];
            
            RJTableCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RJCell" forIndexPath:indexPath];
            cell.title.text = [dataD objectForKey:@"title"];
            cell.time.text = [dataD objectForKey:@"time"];
            cell.name.text = [dataD objectForKey:@"recordName"];
            [cell setType:[dataD objectForKey:@"state"]];
            
            return cell;
        }
    } else {
        indexTableCell *cell=[tableView dequeueReusableCellWithIdentifier:@"index" forIndexPath:indexPath];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        NSDictionary *dict=self.array[indexPath.row];
        //设置文字
        cell.qiandaoUser.text=dict[@"cellText"];
        //判断签到 签退
        if([dict[@"type"] isEqualToString:@"RECORD_05"]){
            cell.line.backgroundColor=[UIColor colorWithRed:0.68 green:0.36 blue:0.63 alpha:1.00];
        }else{
            cell.line.backgroundColor=[UIColor colorWithRed:0.00 green:0.59 blue:0.53 alpha:1.00];
        }
        cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
        //设置时间
        cell.qiandaoDate.text=dict[@"time"];
        return cell;
    }
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // 获取当前角色
    NSString *role=DEF_PERSISTENT_GET_OBJECT(@"role");
    
    if (!_isXJJF && ![role isEqualToString:@"USER_01"] && ![role isEqualToString:@"USER_03"]&& ![role isEqualToString:@"USER_07"]) {
        NSDictionary *dict = self.array[indexPath.row];
        QianDViewController *qiand=[[QianDViewController alloc]init];
        qiand.dict=dict;
        [self.navigationController pushViewController:qiand animated:YES];
        
        // 总监
    } else if ([role isEqualToString:@"USER_01"]) {
        NSDictionary *dic = [self.dataArray objectAtIndex:indexPath.row];
        
        // 督办,跟进
        if ([dic[@"TYPE"] isEqualToString:@"default"]) {
            ProcessModel *pModel = dic[@"DATA"];
            
            DBYSDetailViewController *GJDetail=[[DBYSDetailViewController alloc]init];
            GJDetail.processId = pModel.ID;
            GJDetail.addresInfo = pModel.ADDRES_INFO;
            GJDetail.beginTime = pModel.BEGIN_TIME;
            [self.navigationController pushViewController:GJDetail animated:YES];
            
        //验收
        }else if ([dic[@"TYPE"] isEqualToString:@"ys"]){
        ProcessModel *pModel = dic[@"DATA"];
        JLYSViewController_detail *ysCtr=[[JLYSViewController_detail alloc]init];
        ysCtr.addInfo = pModel.ADDRES_INFO;
        ysCtr.processId = pModel.ID;
        ysCtr.createTime = pModel.MODIFY_TIME;
        ysCtr.processNumber = pModel.PROCESS_NUMBER;
        //跳转到验收信息
        [self.navigationController pushViewController:ysCtr animated:YES];
  
        }
        // 巡检
        else if ([dic[@"TYPE"] isEqualToString:@"inspection"]) {
            NSDictionary *dics = dic[@"DATA"];
            YJHBViewController *yjhbVC = [[YJHBViewController alloc]init];
            yjhbVC.inspectProcessDic = dics;
            [self.navigationController pushViewController:yjhbVC animated:YES];
            
            // 日记
        } else if ([dic[@"TYPE"] isEqualToString:@"diary"]) {
            
            NSDictionary *dataD = dic[@"DATA"];
            ZJRZDetailViewController *detail=[[ZJRZDetailViewController alloc]init];
            //传入id
            detail.diaryId=dataD[@"id"];
            //阅读页
            detail.flag=@"look";
            detail.identity=@"";
            detail.state=[dataD objectForKey:@"state"];
            [self.navigationController pushViewController:detail animated:YES];
            
            // 日志
        } else if ([dic[@"TYPE"] isEqualToString:@"log"]) {
            NSDictionary *dataD = dic[@"DATA"];
            ZJRZViewController_Detail *detail=[[ZJRZViewController_Detail alloc]init];
            detail.logId=dataD[@"id"];
            detail.type=dataD[@"type"];
            detail.state=dataD[@"state"];
            
            [self.navigationController pushViewController:detail animated:YES];
        }
        
        // 监理
    } else if ([role isEqualToString:@"USER_03"]||[role isEqualToString:@"USER_07"]) {
        NSDictionary *dic = [self.dataArray objectAtIndex:indexPath.row];
        ProcessModel *pModel = dic[@"DATA"];
        
        // 监理(督办)
        if (pModel.PROCESS_TYPE == 1) {
            GJDBViewController_Detail *detail=[[GJDBViewController_Detail alloc]init];
            detail.processId = pModel.ID;
            detail.JLDuB = YES;
            detail.addressInfo = pModel.ADDRES_INFO;
            detail.beginTime = pModel.BEGIN_TIME;
            
            //发送类型为无 监理待复查等于待执行 只是点击合格之后变为复查通过。不合格之后仍为待复查。
//            if ([self getSendTypeWithPROCESS_ID:dics[@"id"]] == 4) {
//                GJDetail.daiBDetail = YES;
//                GJDetail.isSendTypeWU = YES;
//            }
            
            SGFDBDetailViewController *GJDetail=[[SGFDBDetailViewController alloc]init];
            GJDetail.flag = @"detail";
            GJDetail.processID = pModel.ID;
            GJDetail.addressInfo = pModel.ADDRES_INFO;
            GJDetail.beginTime = pModel.BEGIN_TIME;
            GJDetail.gengjing = YES;
            
            
            //整改人
            NSString *userid1=pModel.PROCESS_RECIFY_USERS;
            BOOL isjianlidaizhixing = NO;
            if (userid1&&[userid1 isEqualToString:USERID]) {
                isjianlidaizhixing = YES;
            }
            //负责人
            NSString *userid2=pModel.PROCESS_MASTERS;
            BOOL isJianliDaiFuCha = NO;
            if (userid2&&[userid2 isEqualToString:USERID]) {
                isJianliDaiFuCha = YES;
            }
            //
            //监理待执行
            if (isjianlidaizhixing&&pModel.PROCESS_STAGE==PROCESS_STAGE_DOING) {
                GJDetail.edit = YES;
                GJDetail.daiBDetail = YES;
            }
            //监理待复查
            if (isJianliDaiFuCha&&pModel.PROCESS_STAGE==PROCESS_STAGE_CHECK) {
                GJDetail.jianLiDaiFuCha = YES;
            }
          
            
            [self.navigationController pushViewController:GJDetail animated:YES];
            
        // 监理(跟进)
        } else if (pModel.PROCESS_TYPE == 2) {
            SGFDBDetailViewController *GJDetail=[[SGFDBDetailViewController alloc]init];
            GJDetail.flag = @"detail";
            GJDetail.processID = pModel.ID;
            GJDetail.addressInfo = pModel.ADDRES_INFO;
            GJDetail.beginTime = pModel.BEGIN_TIME;
            GJDetail.gengjing = YES;
            
            
            //整改人
            NSString *userid1=pModel.PROCESS_RECIFY_USERS;
            BOOL isjianlidaizhixing = NO;
            if (userid1&&[userid1 isEqualToString:USERID]) {
                isjianlidaizhixing = YES;
            }
//            //发起人
            NSString *userid2=pModel.PROCESS_PUBLISHERS;
            BOOL isJianliDaiFuCha = NO;
            if (userid2&&[userid2 isEqualToString:USERID]) {
                isJianliDaiFuCha = YES;
            }
//
            //监理待执行
            if (isjianlidaizhixing&&pModel.PROCESS_STAGE==PROCESS_STAGE_DOING) {
                GJDetail.edit = YES;
                GJDetail.daiBDetail = YES;
            }
//            //监理待复查
            if (isJianliDaiFuCha&&pModel.PROCESS_STAGE==PROCESS_STAGE_CHECK) {
                GJDetail.jianLiDaiFuCha = YES;
            }
            
        
            
            [self.navigationController pushViewController:GJDetail animated:YES];
            // 验收
        } else if (pModel.PROCESS_TYPE == 3) {
            JLYSViewController_detail *ysCtr=[[JLYSViewController_detail alloc]init];
            ysCtr.addInfo = pModel.ADDRES_INFO;
            ysCtr.processId = pModel.ID;
            ysCtr.createTime = pModel.MODIFY_TIME;
            ysCtr.processNumber = pModel.PROCESS_NUMBER;
            //跳转到验收信息
            [self.navigationController pushViewController:ysCtr animated:YES];
        }
    }
}

#pragma mark - 查询本地数据表 是否有ADD 或者 MOD数据
- (BOOL)queayLocalDataContainAddOrModByTableFormsg:(NSString *)table{
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sql=@"";
    if([table isEqualToString:WORK_RECORD]){
        
        sql=[NSString stringWithFormat:@"SELECT ID,RECORD_TYPE,LOCAL_MODIFY_STATE FROM %@ WHERE LOCAL_MODIFY_STATE IN('ADD','MOD','DEL')",table];
        
    }else if ([table isEqualToString:PROCESS]||[table isEqualToString:PROCESS_RECORD]){
        
        sql=[NSString stringWithFormat:@"SELECT ID,PROCESS_TYPE,LOCAL_MODIFY_STATE FROM %@ WHERE LOCAL_MODIFY_STATE IN('ADD','MOD','DEL')",table];
        
    }
    else{
        
        sql=[NSString stringWithFormat:@"SELECT ID,MODIFY_TIME,LOCAL_MODIFY_STATE FROM %@ WHERE LOCAL_MODIFY_STATE IN('ADD','MOD','DEL')",table];
        
    }
    FMResultSet *resule=[db executeQuery:sql];
    BOOL isExist=NO;
    while ([resule next]) {
        
        isExist=YES;
        //记录表
        if([table isEqualToString:WORK_RECORD]){
            NSString *type=[resule stringForColumn:@"RECORD_TYPE"];
            if([type isEqualToString:@"RECORD_01"]){
                self.syncType=TEXT_SYNC_XS;
            }else if([type isEqualToString:@"RECORD_02_01"]||[type isEqualToString:@"RECORD_02_02"]||[type isEqualToString:@"RECORD_02_03"]||[type isEqualToString:@"RECORD_02_04"]||[type isEqualToString:@"RECORD_02_05"]){
                self.syncType=TEXT_SYNC_PZ;
            }else if ([type isEqualToString:@"RECORD_03"]){
                self.syncType=TEXT_SYNC_AQ;
            }else if ([type isEqualToString:@"RECORD_04"]){
                self.syncType=TEXT_SYNC_QT;
            }else if ([type isEqualToString:@"RECORD_05"]){
                self.syncType=TEXT_SYNC_SIGNIN;
            }else if ([type isEqualToString:@"RECORD_06"]){
                self.syncType=TEXT_SYNC_SIGNOUT;
            }else if ([type isEqualToString:@"RECORD_07"]){
                self.syncType=TEXT_SYNC_JCJL;
            }else if ([type isEqualToString:@"RECORD_08"]){
                self.syncType=TEXT_SYNC_ZLJL;
            }else if ([type isEqualToString:@"RECORD_09"]){
                self.syncType=TEXT_SYNC_JDJL;
            }else if ([type isEqualToString:@"RECORD_10"]){
                self.syncType=TEXT_SYNC_CLJL;
            }else if ([type isEqualToString:@"RECORD_11"]){
                self.syncType=TEXT_SYNC_YBJL;
            }else if ([type isEqualToString:@"RECORD_12"]){
                self.syncType=TEXT_SYNC_SFWJL;
            }else if ([type isEqualToString:@"RECORD_13"]){
                self.syncType=TEXT_SYNC_JZJL;
            }else if ([type isEqualToString:@"RECORD_14"]){
                self.syncType=TEXT_SYNC_HYJL;
            }
        }
        
        //日记表
        if([table isEqualToString:WORK_DIARY]){
            self.syncType=TEXT_SYNC_RJ;
        }
        
        //日志表
        if([table isEqualToString:WORK_LOG]){
            self.syncType=TEXT_SYNC_RZ;
        }
        
        //流程表
        if([table isEqualToString:PROCESS]){
            NSString *type=[resule stringForColumn:@"PROCESS_TYPE"];
            if([type isEqualToString:@"1"]){
                self.syncType=TEXT_SYNC_DB;
            }else if ([type isEqualToString:@"2"]){
                self.syncType=TEXT_SYNC_GJ;
            }else if ([type isEqualToString:@"3"]){
                self.syncType=TEXT_SYNC_YS;
            }
        }
        //流程记录表
        if([table isEqualToString:PROCESS_RECORD]){
            NSString *type=[resule stringForColumn:@"PROCESS_TYPE"];
            if([type isEqualToString:@"1"]){
                self.syncType=TEXT_SYNC_DBJL;
            }else if ([type isEqualToString:@"2"]){
                self.syncType=TEXT_SYNC_GJJL;
            }else if ([type isEqualToString:@"3"]){
                self.syncType=TEXT_SYNC_YSJL;
            }
        }
        
        //见证取样表
        if([table isEqualToString:SAMPLE_PROCESS]){
            self.syncType= TEXT_SYNC_JZQY;
        }
        
        //见证取样流程
        if([table isEqualToString:SAMPLE_PROCESS_RECORD]){
            self.syncType= TEXT_SYNC_JZQYJL;
        }
        
        //工程巡检表
        if([table isEqualToString:INSPECT_PROCESS]){
            self.syncType= TEXT_SYNC_GCXJ;
        }
        
        //工程巡检记录表
        if([table isEqualToString:INSPECT_PROCESS_RECORD]){
            self.syncType= TEXT_SYNC_GCXJJL;
        }
        
        //一键汇总
        if([table isEqualToString:INSPECT_TOTAL_RECORD]){
            self.syncType= TEXT_SYNC_GCXJHZ;
        }
        
        if([table isEqualToString:ATTACHMENT]){
            self.syncType= @"附件上传失败";
        }
        //结束循环
        break;
    }
    [db close];
    return isExist;
}

- (BOOL)queayLocalDataContainAddOrModByTable:(NSString *)table{
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sql=[NSString stringWithFormat:@"SELECT ID,MODIFY_TIME,LOCAL_MODIFY_STATE FROM %@ WHERE LOCAL_MODIFY_STATE IN('ADD','MOD','DEL')",table];
    FMResultSet *resule=[db executeQuery:sql];
    BOOL hidden=YES;
    while ([resule next]) {
        hidden=NO;
    }
    [db close];
    return hidden;
}

#pragma  mark -轮播图点击

/** 点击图片回调 */
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index{
    //    NSLog(@"%ld",index);
    if(self.advArr.count>0){
        AdvertisementController *advCtr=[[AdvertisementController alloc]init];
        NSMutableDictionary *dic=self.advArr[index];
        //标题图片
        [dic setObject:self.advImageArr[index] forKey:@"img"];
        //内容图片路径拼接ip地址
        NSString *text=dic[@"TEXT"];
        NSString *ipText=[text stringByReplacingOccurrencesOfString:@"attachments" withString:[NSString stringWithFormat:@"%@/attachments",API_HOST]];
        //重新设置
        [dic setObject:ipText forKey:@"text"];
        advCtr.davDic=dic;
        [self.navigationController pushViewController:advCtr animated:YES];
    }
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
-(void)oldWeatherParame{
    //NSLog(@"userID:%@",USERID);
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    DBHelper *helper=[DBHelper help];
    //根据id查询到项目
    NSArray *proIdArr=[helper DataBase:db selectStr:@"distinct(PRO_ID)" selectKeyTypes:@{@"PRO_ID":@"text"} fromTable:PROJECT_USER whereCondition:@{@"USER_ID":USERID}];
    NSMutableArray *idArr=[NSMutableArray array];
    for (NSDictionary *dic in proIdArr) {
        [idArr addObject:dic[@"PRO_ID"]];
    }
    NSString *parame=[LSUtility dictionaryToJson_2:idArr];
    NSMutableString *mutStr = [NSMutableString
                               stringWithString:parame];
    NSRange range = {0,mutStr.length};
    [mutStr replaceOccurrencesOfString:@"["
                            withString:@""
                               options:NSLiteralSearch range:range];
    
    NSRange range1 = {0,mutStr.length};
    [mutStr replaceOccurrencesOfString:@"]"
                            withString:@""
                               options:NSLiteralSearch range:range1];
    //    [parmeDic setObject:mutStr forKey:@"localdata"];
    
    //        [LSHttpTool Post:URL_WEATHER_SELECT parameters:parmeDic success:^(id responseObject) {
    //            NSString *code=responseObject[@"code"];
    //            if([code isEqualToString:@"1"]){
    //                DeLog(@"array:%@",responseObject);
    //                [self getWeather:responseObject[@"data"]];
    //            } else{
    //                [LSUtility showToastWithMessage:@"天气获取失败" inView:self.view Andtime:1.];
    //            }
    //        } failure:^(NSError *error) {
    //
    //            [LSUtility showToastWithMessage:@"天气获取失败" inView:self.view Andtime:1.];
    //        }];
    
}

@end
